package cn.kow.kmall.service.impl;

import cn.kow.kmall.common.enums.KmallResultEnum;
import cn.kow.kmall.core.constant.KmallStatusConstant;
import cn.kow.kmall.core.exception.ServiceException;
import cn.kow.kmall.dao.OrderItemRepository;
import cn.kow.kmall.dao.OrderRepository;
import cn.kow.kmall.pojo.dto.OrderQueryDTO;
import cn.kow.kmall.pojo.entity.Order;
import cn.kow.kmall.pojo.entity.OrderItem;
import cn.kow.kmall.service.OrderService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 *
 */
@Service("orderService")
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private OrderItemRepository orderItemRepository;

    @Override
    public Page<Order> listByPage(OrderQueryDTO queryDTO) {
        if (StringUtils.isBlank(queryDTO.getOrderBy())) {
            queryDTO.setOrderBy("createTime desc");
        }
        Page<Order> page = orderRepository.queryByPage(queryDTO);
        return page;
    }

    @Override
    public Order createOrder(Order order, List<OrderItem> orderItemList) {
        String orderNo = createOrderNo();
        order.setOrderNo(orderNo);
        orderItemList.stream().forEach(i -> {
            i.setOrderNo(orderNo);
            i.setRefundNum(0);
            i.setDeleted(false);
            i.setRemark("");
            i.setStatus(KmallStatusConstant.NORMAL);
            i.setCreateTime(new Date());
        });
        orderRepository.create(order);
        orderItemRepository.saveAll(orderItemList);
        return order;
    }

    /**
     * 订单号获取订单
     * @param orderNo   订单号
     * @return  订单
     */
    @Override
    public Order getOrder(String orderNo) {
        Order exampleOrder = new Order();
        exampleOrder.setOrderNo(orderNo);
        exampleOrder.setStatus(KmallStatusConstant.NORMAL);
        exampleOrder.setDeleted(false);
        Example<Order> example = Example.of(exampleOrder);
        return orderRepository.findOne(example).orElseThrow(() -> new ServiceException(KmallResultEnum.ORDER_NOT_EXIST));
    }

    /**
     * 更新订单
     * @param order 订单
     */
    @Override
    public void updateOrder(Order order) {
        if (order.getId() == null) {
            throw new ServiceException(KmallResultEnum.ORDER_NOT_EXIST);
        }
        orderRepository.update(order);
    }

    /**
     *
     * @param orderNo
     * @return
     */
    @Override
    public List<OrderItem> listOrderItem(String orderNo) {
        OrderItem exampleOrderItem = new OrderItem();
        exampleOrderItem.setOrderNo(orderNo);
        exampleOrderItem.setStatus(KmallStatusConstant.NORMAL);
        return orderItemRepository.findAll(Example.of(exampleOrderItem));
    }

    /**
     *
     * @param orderNo
     * @return
     */
    @Override
    public List<OrderItem> listOrderItemByLimit(String orderNo, Integer limit) {
        OrderItem exampleOrderItem = new OrderItem();
        exampleOrderItem.setOrderNo(orderNo);
        exampleOrderItem.setStatus(KmallStatusConstant.NORMAL);
        Pageable pageable = PageRequest.of(0, limit);
        Page<OrderItem> page = orderItemRepository.findAll(Example.of(exampleOrderItem), pageable);
        if (page.hasContent()) {
            return page.getContent();
        } else {
            return new ArrayList<>();
        }
    }

    @Override
    public void updateOrderItem(OrderItem orderItem) {
        if (orderItem.getId() == null) {
            throw new ServiceException(KmallResultEnum.ORDER_NOT_EXIST);
        }
        orderItemRepository.update(orderItem);
    }


    /**
     * 创建订单商品
     * @param orderNo   订单号
     * @param itemId    商品ID
     * @param skuId     skuId
     * @param num       数量
     * @param unitPrice 单价
     * @param totalPrice 总价
     * @param name      商品名称
     * @param spec      规格
     * @param pic       图片
     */
    private void createOrderItem(String orderNo, Long itemId, Long skuId, Integer num, Integer unitPrice,
                                 Integer totalPrice, String name, String spec, String pic) {
        OrderItem orderItem = new OrderItem();
        orderItem.setOrderNo(orderNo);
        orderItem.setItemId(itemId);
        orderItem.setSkuId(skuId);
        orderItem.setBuyNum(num);
        orderItem.setUnitPrice(unitPrice);
        orderItem.setTotalFee(totalPrice);
        orderItem.setItemName(name);
        orderItem.setItemSpec(spec);
        orderItem.setItemPic(pic);
        orderItem.setRemark("");
        orderItem.setStatus(KmallStatusConstant.NORMAL);
        orderItem.setCreateTime(new Date());
        orderItemRepository.save(orderItem);
    }

    /**
     * 生成订单号
     * @return 订单号
     */
    private String createOrderNo() {
        LocalDateTime dateTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyMMddHHmmss");
        Random rand = new Random();
        int i = rand.nextInt(7) + 1;
        int j = rand.nextInt(10);
        int k = rand.nextInt(10);
        String orderNo = i + dateTime.format(formatter) + j + k;
        return orderNo;
    }
}
